﻿using System;
using UnityEngine;
using UnityEngine.Events;

namespace BToolkit
{
    [AddComponentMenu("BToolkit/StateButtonsGroup")]
    public class StateButtonsGroup : MonoBehaviour
    {
        public StateButton[] buttons;
        [System.Serializable]
        public class ValueEvent : UnityEvent<int> { }
        public ValueEvent onValueChange;

        void Awake()
        {
            for (int i = 0; i < buttons.Length; i++)
            {
                StateButton button = buttons[i];
                if (button)
                {
                    button.index = i;
                    button.onValueChanged.AddListener(OnToggleChange);
                }
            }
        }

        public void SetButtons(StateButton[] buttons, int defaultShowIndex)
        {
            this.buttons = buttons;
            for (int i = 0; i < buttons.Length; i++)
            {
                StateButton button = buttons[i];
                if (button)
                {
                    button.index = i;
                    button.onValueChanged.AddListener(OnToggleChange);
                }
            }
            SetDefaultOn(defaultShowIndex);
        }

        void OnToggleChange(int index, bool isOn)
        {
            if (isOn)
            {
                for (int i = 0; i < buttons.Length; i++)
                {
                    StateButton button = buttons[i];
                    if (i != index)
                    {
                        button.IsOn = false;
                    }
                    button.enabled = (i != index);
                }
                if (onValueChange != null)
                {
                    onValueChange.Invoke(index);
                }
            }
        }

        public void SetDefaultOn(int index)
        {
            if (index < 0) index = 0;
            if (index > buttons.Length - 1) index = buttons.Length - 1;
            for (int i = 0; i < buttons.Length; i++)
            {
                StateButton button = buttons[i];
                button.IsOn = (i == index);
                button.enabled = (i != index);
            }
            if (onValueChange != null)
            {
                onValueChange.Invoke(index);
            }
        }
    }
}